<template>
  <div class="zzh_webSocket"></div>
</template>

<script>
import SockJS from 'sockjs-client';
import { Stomp } from '@stomp/stompjs';
export default {
  name: 'zzh_webSocket',
  data() {
    return {
      websocketUrl: "http://localhost:8099/ws",
      topicUrl:"/topic/warning",
      webSocket: null, //socket对象
      stompClient: null,
    };
  },
  methods: {
    initWebSocket() {
        this.webSocket = new SockJS(this.websocketUrl); //创建socket对象
        this.stompClient=Stomp.over(this.webSocket);
    },
    //收到消息
    webSocketOnMessage() {
      this.stompClient.connect({}, (frame) => {
        // 订阅主题以接收消息
        this.stompClient.subscribe(this.topicUrl, (message) => {
          const res = JSON.parse(JSON.stringify(message.body));
          this.$emit("warningEvent",res)
        });
      }, (error) => {
        console.error('STOMP error:', error);
      });
    },
  },
  created() {
    this.initWebSocket();
  },
  mounted() {
    this.webSocketOnMessage();
  },
};
</script>

<style lang="less">

</style>
